package com.ontheroad.mysql.collect.service;

import cn.modoumama.page.PageObject;
import cn.modoumama.service.base.impl.BaseServiceImpl;
import com.ontheroad.api.request.CollectRequest;
import com.ontheroad.api.request.Request;
import com.ontheroad.api.response.Response;
import com.ontheroad.collect.modle.CollectModel;
import com.ontheroad.collect.service.CollectService;
import com.ontheroad.mysql.collect.mapper.CollectMapper;
import com.ontheroad.mysql.path.mapper.PathUserMapper;
import com.ontheroad.path.model.PathUserModel;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kedong on 2017/7/2 0002.
 */
@Service
@Transactional
public class CollectServiceImpl extends BaseServiceImpl<CollectModel, Integer> implements CollectService {

    @Autowired
    private CollectMapper mapper;
    @Autowired
    private PathUserMapper pathUserMapper;

    @Autowired
    public void setMapper(CollectMapper mapper) {
        setGenericMapper(mapper);
    }

    @Override
    public Response getCollections(Request request) throws Exception {
        Integer userId = request.getUserId().intValue();
        PageObject po = new PageObject();
        po.setCurrPage(request.getPageNum());
        po.setPageSize(request.getPageSize());
        RowBounds rowBounds = new RowBounds(po.getOffset(), po.getPageSize());
        List<Integer> pathIds = mapper.findPathIds(userId, rowBounds);
        List<PathUserModel> pathUserModels = new ArrayList<>();
        if (pathIds != null && pathIds.size() > 0) {
            pathUserModels = pathUserMapper.findPathByIds(pathIds);
        }
        Response response = Response.SUCCESS();
        response.addResultData("collections", pathUserModels);
        return response;
    }

    @Override
    public Response addCollection(CollectRequest request) throws Exception {
        Integer pathId = request.getPathId();
        Integer userId = request.getUserId().intValue();
        CollectModel collectModel = new CollectModel();
        collectModel.setPathid(pathId);
        collectModel.setUserid(userId);
        insert(collectModel);
        return Response.SUCCESS();
    }

    @Override
    public Response cancelCollection(CollectRequest request) throws Exception {
        Integer pathId = request.getPathId();
        Integer userId = request.getUserId().intValue();

        mapper.deleteCollection(pathId, userId);

        return Response.SUCCESS();
    }
}
